﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XWPF.UserModel;
using System;
using System.IO;
using System.Windows.Forms;
using Xceed.Words.NET;

namespace ExcelToOtherDocument
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 选择文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelect_Click(object sender, EventArgs e)
        {

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                txtFilePath.Text = openFileDialog1.FileName;
            }

        }
        /// <summary>
        /// 批量生成word文件每一行生成一个单独的文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        [Obsolete]
        private void btnCreate_Click(object sender, EventArgs e)
        {
            using (FileStream file = new FileStream(txtFilePath.Text, FileMode.Open, FileAccess.Read))
            {
                IWorkbook workbook = new HSSFWorkbook(file); // 使用 XSSFWorkbook 读取.xlsx格式的文件
                ISheet sheet = workbook.GetSheetAt(0); // 获取第一个工作表

                int rowCount = sheet.LastRowNum + 1;
                DateTime now = DateTime.Now;
                int year = now.Year;
                int month = now.Month;
                int days = now.Day;
                // 循环保存文档
                string templatePath = "template.docx";
                string outputPath =txtOutPath.Text;
                if (!Directory.Exists(outputPath))
                {
                    Directory.CreateDirectory(outputPath);
                }
                for (int i = 0; i < rowCount; i++)
                {
                    IRow row = sheet.GetRow(i);
                    if (row != null)
                    {
                        // 商铺名称	商铺位置	"抄表起数"	"抄表止数"	实际用电度数	本期用电度数	"用电倍率"	电费单价	本期电费
                        int colCount = row.LastCellNum;

                        // 打开模板文件
                        using (DocX templateDoc = DocX.Load(templatePath))
                        {

                            // 替换模板中的占位符
                            if (row.GetCell(0) == null)
                            {
                                continue;
                            }
                            templateDoc.ReplaceText("{商铺名称}", row.GetCell(0).ToString());
                            templateDoc.ReplaceText("{年}", year.ToString());
                            templateDoc.ReplaceText("{月}", month.ToString());
                            templateDoc.ReplaceText("{日}", days.ToString());

                            templateDoc.ReplaceText("{店铺位置}", row.GetCell(1).ToString());
                            templateDoc.ReplaceText("{抄表起数}", row.GetCell(2).ToString());
                            templateDoc.ReplaceText("{抄表止数}", row.GetCell(3).ToString());
                            templateDoc.ReplaceText("{实际用电}", row.GetCell(4).ToString());
                            templateDoc.ReplaceText("{用电倍率}", row.GetCell(5).ToString());
                            templateDoc.ReplaceText("{本期用电度数}", row.GetCell(6).ToString());
                            templateDoc.ReplaceText("{电费单价}", row.GetCell(7).ToString());
                            string str = row.GetCell(8).ToString();
                            if (string.IsNullOrWhiteSpace(str))
                            {

                                int fee = (int)Math.Round(Convert.ToDouble(str));
                                templateDoc.ReplaceText("{本期电费}", fee.ToString());
                            }
                            else
                            {
                                templateDoc.ReplaceText("{本期电费}", row.GetCell(8).ToString());
                            }

                            // 保存生成的 Word 文档
                            templateDoc.SaveAs(outputPath + row.GetCell(0) + ".docx");
                        }

                    }
                }
                               
                MessageBox.Show("批量生成Word成功");
            }

        }

        /// <summary>
        /// 合并word
        /// </summary>
        /// <param name="folderPath"></param>
        /// <param name="mergedDocumentPath"></param>
        static void MergeDocuments(string folderPath, string mergedDocumentPath)
        {
            string[] documentPaths = Directory.GetFiles(folderPath, "*.docx");

            using (DocX mergedDoc = DocX.Create(mergedDocumentPath))
            {
                foreach (string documentPath in documentPaths)
                {
                    using (DocX doc = DocX.Load(documentPath))
                    {
                        foreach (var paragraph in doc.Paragraphs)
                        {
                            mergedDoc.InsertParagraph();


                        }
                    }
                }

                mergedDoc.Save();
            }
        }

        /// <summary>
        /// 合并为一个word文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        [Obsolete]
        private void btnCreateMerged_Click(object sender, EventArgs e)
        {
            using (FileStream file = new FileStream(txtFilePath.Text, FileMode.Open, FileAccess.Read))
            {
                IWorkbook workbook = new HSSFWorkbook(file); // 使用 XSSFWorkbook 读取.xlsx格式的文件
                ISheet sheet = workbook.GetSheetAt(0); // 获取第一个工作表

                int rowCount = sheet.LastRowNum + 1;
                DateTime now = DateTime.Now;
                int year = now.Year;
                int month = now.Month;
                int days = now.Day;
                // 循环保存文档
                string templatePath = "template.docx";
                string outputPath = txtOutPath.Text;
                if (!Directory.Exists(outputPath))
                {
                    Directory.CreateDirectory(outputPath);
                }
                // 创建新的Word文档  
                DocX wordDocument = DocX.Create(outputPath + "合并后.docx");
               
                for (int i = 0; i < rowCount; i++)
                {
                    IRow row = sheet.GetRow(i);
                    if (row != null)
                    {                        
                                    
                        // 商铺名称	商铺位置	"抄表起数"	"抄表止数"	实际用电度数	本期用电度数	"用电倍率"	电费单价	本期电费
                        int colCount = row.LastCellNum;
                        // 打开模板文件
                        using (DocX templateDoc = DocX.Load(templatePath))
                        {
                            // 替换模板中的占位符
                            if (row.GetCell(0) == null)
                            {
                                continue;
                            }
                            templateDoc.ReplaceText("{商铺名称}", row.GetCell(0).ToString());
                            templateDoc.ReplaceText("{年}", year.ToString());
                            templateDoc.ReplaceText("{月}", month.ToString());
                            templateDoc.ReplaceText("{日}", days.ToString());

                            templateDoc.ReplaceText("{店铺位置}", row.GetCell(1).ToString());
                            templateDoc.ReplaceText("{抄表起数}", row.GetCell(2).ToString());
                            templateDoc.ReplaceText("{抄表止数}", row.GetCell(3).ToString());
                            templateDoc.ReplaceText("{实际用电}", row.GetCell(4).ToString());
                            templateDoc.ReplaceText("{用电倍率}", row.GetCell(5).ToString());
                            templateDoc.ReplaceText("{本期用电度数}", row.GetCell(6).ToString());
                            templateDoc.ReplaceText("{电费单价}", row.GetCell(7).ToString());
                            string str = row.GetCell(8).ToString();
                            if (string.IsNullOrWhiteSpace(str))
                            {
                                int fee = (int)Math.Round(Convert.ToDouble(str));
                                templateDoc.ReplaceText("{本期电费}", fee.ToString());
                            }
                            else
                            {
                                templateDoc.ReplaceText("{本期电费}", row.GetCell(8).ToString());
                            }
                            wordDocument.InsertDocument(templateDoc);
                          
                        }
                    }
                  
                }
                wordDocument.Save();
                MessageBox.Show("批量生成Word成功");
            }
        }
    }
}
